

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse, reverse_lazy
from django.views.generic import ListView, DeleteView, DetailView

from main.models import ArticleModel
from user.forms import RegistForm, LoginForm, ChangePasswordForm
from django.contrib.auth import authenticate, login as lgi, logout as lgo
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib import messages

from user.models import CustomUser
from django.contrib.auth.decorators import login_required

# Create your views here.
@login_required()
def changepwd(request):
    if request.method == 'POST':
        cp = ChangePasswordForm(request.POST)
        if cp.is_valid():
            if request.user.check_password(cp.cleaned_data['old_password']):
                request.user.set_password(cp.cleaned_data['new_password'])
                request.user.save()
                messages.success(request,'密码修改成功')
                lgo( request)
                return redirect(reverse('user:login'))
            else:
                cp.add_error('old_password','原始密码不正确')
                return render(request,'main/changepwd.html',{'form':cp})
        else:
            return render(request,'main/changepwd.html',{'form':cp})
    return render(request,'main/changepwd.html',{'form':ChangePasswordForm()})
@login_required
def center(request):
    if not request.user.is_authenticated:
        return redirect(reverse('user:login'))

    head = request.user.head
    print("==========================", head)

    if request.method == 'POST':
        form = PasswordChangeForm(user=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()
            # 保持用户会话，不用重新登录
            update_session_auth_hash(request, user)
            messages.success(request, '密码已成功修改')
            return redirect(reverse('user:center'))
        else:
            messages.error(request, '密码修改失败，请检查表单输入')
    else:
        form = PasswordChangeForm(user=request.user)

    return render(request, 'main/center.html', {
        'head': head,
        'form': form,
    })


def rigest(request):
    if request.method == "POST":
        rf = RegistForm(request.POST)

        if rf.is_valid():
            user = rf.save(commit=False)
            print(user,'999999999')
            user.set_password(rf.cleaned_data['password'])
            user.username = rf.cleaned_data['email']
            user.is_active = False
            user.is_staff = True
            user.is_superuser = True
            user.save()
            user.email_user('欢迎注册',message='',html_message=f'<a href="http://127.0.0.1:8000/user/active/{user.id}">点击我激活</a>')
            return redirect(reverse('user:login'))
        else:
            print('-------------',rf.errors)
            return render(request,'main/rigest.html',context={'form':rf})

    return  render(request,'main/rigest.html',context={'form':RegistForm()})

def active(request,id):
    user = CustomUser.objects.filter(id=id).first()
    if user:
        user.is_active = True
        user.save()
        return redirect(reverse('user:login'))
        # return  render(request,'main/login.html')
    else:
        return HttpResponse('激活失败')

def login(request):
    if request.method == "POST":
        rf = LoginForm(request.POST)

        if rf.is_valid():
            user = CustomUser.objects.filter(email=rf.cleaned_data['username']).first() or CustomUser.objects.filter(username=rf.cleaned_data['username']).first()
            if user.is_active:

                lgi(request,user)
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url)
                return redirect(reverse('main:index'))
            else: rf.add_error('username','用户未激活')
            return render(request, 'main/login.html', context={'form': rf})

        else:
            return render(request,'main/login.html',context={'form':rf})
    return render(request,'main/login.html',context={'form':LoginForm()})


def logout(request):
    lgo(request)
    return redirect(reverse('user:login'))

class AritcleModleListView(ListView):
    paginate_by = 1
    model = ArticleModel

class ArticleManagerListView(ListView):
    template_name = 'main/manage.html'
    paginate_by = 2
    model = ArticleModel

class AritcleModleDeleteView(DeleteView):
    template_name = 'main/articlemodel_confirm_delete.html'
    success_url = reverse_lazy('main:index')
    model = ArticleModel
class ArticleModleDetailView(DetailView):

    queryset = ArticleModel.objects.all()
    template_name = 'main/article_detail.html'